import requests
from webapp.config import Config


def get_image_api(filename: str):
    if filename[0] in ['a', 'b', 'c', 'd', 'e', 'f']:
        return Config.IMAGE_API_2
    else:
        return Config.IMAGE_API_1


def get_image_host(file_name: str):
    if file_name[0] in ['a', 'b', 'c', 'd', 'e', 'f']:
        return Config.IMAGE_HOST_2
    else:
        return Config.IMAGE_HOST_1


def get_image_url(filename: str):
    return f'{get_image_host(filename)}/pic/{filename[:2]}/{filename}'


def get_thumb_url(filename_no_suffix: str):
    return f'{get_image_host(filename_no_suffix)}/sm/{filename_no_suffix[:2]}/{filename_no_suffix}'


def upload_image_file(filename, img, thumb=None):
    """生成图片缩略图并且把图片放入piclab"""
    url = f'{Config.IMAGE_API_1}/image/images'
    files = {'image': (filename, img)}
    if thumb:
        files['thumb'] = (filename, thumb)

    resp = requests.post(
        url,
        data={'image_api': get_image_api(filename), 'thumb_width': Config.THUMB_WIDTH},
        files=files,
    )
    if resp.status_code == 200:
        return resp.json()['data']
    return


def delete_image_file(filename):
    """删除图片和缩略图"""
    url = f'{get_image_api(filename)}/image/images'
    requests.delete(url, json={'files': [filename]})
    return
